//
//  ZCTaskViewController.m
//  kangbs
//
//  Created by 高睿婕 on 2018/8/14.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCTaskViewController.h"
#import "ZCTaskTitleView.h"
#import "ZCTaskListTableViewCell.h"
#import "ZCTaskTotalNumTableViewCell.h"
#import "ZCTaskModel.h"
#import "ZCTakeCarDetailViewController.h"


static NSString *taskListCell = @"ZCTaskListTableViewCell";
static NSString *taskTotalNumCell = @"ZCTaskTotalNumTableViewCell";

@interface ZCTaskViewController ()<ZCTaskTitleViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) ZCTaskTitleView *taskTitleView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *taskArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger taskType;
@property (nonatomic, strong) ZCTaskPageInfoModel *pageInfoModel;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCTaskViewController
#pragma mark - 懒加载
- (NSMutableArray *)taskArray {
    if (!_taskArray) {
        _taskArray = [NSMutableArray array];
    }
    return _taskArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, space(80) + 64, SCREENWIDTH, SCREENHEIGHT - space(80) - 64 - 49) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = ZCColor(0xf7f8fb, 1);
        
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        
        [_tableView registerClass:[ZCTaskListTableViewCell class] forCellReuseIdentifier:taskListCell];
        [_tableView registerClass:[ZCTaskTotalNumTableViewCell class] forCellReuseIdentifier:taskTotalNumCell];
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    }
    return _tableView;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"个人任务";
    self.taskTitleView = [[ZCTaskTitleView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, space(80))];
    self.taskTitleView.delegate = self;
    self.taskTitleView.titleArray = @[@"已开始", @"已完成"];
    [self.view addSubview:self.taskTitleView];
    
    [self.view addSubview:self.tableView];
    self.taskType = 20;
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    self.page = 1;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    [self loadDataWithTaskType:self.taskType];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
}

#pragma mark - 网络请求
- (void)loadNewData {
    [self loadDataWithTaskType:self.taskType];
}

- (void)loadDataWithTaskType:(NSInteger)type {
    self.page = 1;
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:@(type) forKey:@"taskType"];
        [params setObject:@(self.page) forKey:@"pageNo"];
        [params setObject:@(10) forKey:@"pageSize"];
        NSString *originId = [[NSUserDefaults standardUserDefaults] objectForKey:UserOriginId];
        if (originId.length > 0) {
            [params setObject:originId forKey:@"pointId"];
        }
        
        [ZCHttpTool postWithURL:MyTask params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                [weakSelf.hud hideAnimated:YES];
                [weakSelf.taskArray removeAllObjects];
                NSArray *dataArray = responseObject[@"data"];
                for (NSDictionary *dic in dataArray) {
                    ZCTaskModel *taskModel = [ZCTaskModel yy_modelWithDictionary:dic];
                    [weakSelf.taskArray addObject:taskModel];
                }
                NSDictionary *pageDic = responseObject[@"pageVo"];
                weakSelf.pageInfoModel = [ZCTaskPageInfoModel yy_modelWithDictionary:pageDic];
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView reloadData];
                if (dataArray.count < 10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }else {
                    [weakSelf.tableView.mj_footer resetNoMoreData];
                }
                [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:YES];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:YES];
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
    
}

- (void)loadMoreData {
    [self loadMoreDataWithTaskType:self.taskType];
}

- (void)loadMoreDataWithTaskType:(NSInteger)type {
    self.page++;
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    if (self.page <= [self.pageInfoModel.totalPage integerValue]) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:@(type) forKey:@"taskType"];
            [params setObject:@(self.page) forKey:@"pageNo"];
            [params setObject:@(10) forKey:@"pageSize"];
            NSString *originId = [[NSUserDefaults standardUserDefaults] objectForKey:UserOriginId];
            if (originId.length > 0) {
                [params setObject:originId forKey:@"pointId"];
            }
            
            [ZCHttpTool postWithURL:MyTask params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"success"] boolValue]) {
                    [weakSelf.hud hideAnimated:YES];
                    NSArray *dataArray = responseObject[@"data"];
                    for (NSDictionary *dic in dataArray) {
                        ZCTaskModel *taskModel = [ZCTaskModel yy_modelWithDictionary:dic];
                        [weakSelf.taskArray addObject:taskModel];
                    }
                    self.pageInfoModel = [ZCTaskPageInfoModel yy_modelWithDictionary:responseObject[@"pageVo"]];
                    [weakSelf.tableView reloadData];
                    if (dataArray.count < 10) {
                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                }else {
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                }
                
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                self.page--;
                [weakSelf.tableView.mj_footer endRefreshing];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }];
        });
    }else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    
}

#pragma mark - ZCTaskTitleViewDelegate
- (void)taskTitleViewButttonWithTitle:(NSString *)title {
    if ([title isEqualToString:@"已开始"]) {
        self.taskType = 20;
    }else if ([title isEqualToString:@"已完成"]) {
        self.taskType = 30;
    }
    [self loadDataWithTaskType:self.taskType];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.taskArray.count + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        ZCTaskTotalNumTableViewCell *numCell = [tableView dequeueReusableCellWithIdentifier:taskTotalNumCell forIndexPath:indexPath];
        numCell.selectionStyle = UITableViewCellSelectionStyleNone;
        numCell.num = [self.pageInfoModel.totalRecord integerValue];
        numCell.line = NO;
        return numCell;
    }else {
        
        ZCTaskListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:taskListCell forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        ZCTaskModel *taskModel = (ZCTaskModel *)self.taskArray[indexPath.section-1];
        cell.taskModel = taskModel;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return space(80);
    }else {
        return space(360);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section > 0) {
        ZCTakeCarDetailViewController *detailVC = [[ZCTakeCarDetailViewController alloc] init];
        ZCTaskModel *taskModel = (ZCTaskModel *)self.taskArray[indexPath.section - 1];
        detailVC.taskId = taskModel.taskId;
        detailVC.taskType = taskModel.taskType;
        detailVC.fromSearch = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
}




@end
